//
//  ViewController.m
//  tentecthORC
//
//  Created by 湖南机友科技有限公司 on 2018/3/22.
//  Copyright © 2018年 湖南机友科技有限公司. All rights reserved.
//

#import "ViewController.h"
#import <AFNetworking.h>
#import "HYBNetworking.h"
#import "HBValidateM.h"
#import <MJExtension.h>
#import<CommonCrypto/CommonDigest.h>
#import "UIImage+Extended.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSInteger timeCount=[[HBValidateM getCurrentTimes] integerValue]/1000;


    UIImage *originImage = [UIImage imageNamed:@"1000.png"];

    ///第一总
    NSString * originImageBase64=[originImage base64String];

    ///第二总
    NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
    NSString *encodedImageStr = [data base64Encoding];

    ///第三总
    NSString *encodedImageStrc = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];


    NSString *  urlString = [originImageBase64 stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];


    NSString *urlEncodingString = [originImageBase64 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // uppercaseString];
      NSString* string2 = [originImageBase64 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


    
    NSLog(@"第一总图标编码格式 ==%@",originImageBase64);
    NSLog(@"第二宗图片编码格式 ==%@",encodedImageStr);
    NSLog(@"第三宗图片编码格式 ==%@",encodedImageStrc);

    NSString *timeStr=[NSString stringWithFormat:@"%zd",timeCount];

    NSString *randomStr=[self createUuid];

    NSDictionary *params = @{
                              @"app_id":@"1106795032",
                              @"image":encodedImageStr,
                              @"time_stamp":timeStr,
                              @"nonce_str":randomStr,
                              @"sign":@"8BFE1F361F14A57F53C2984F67227010"
                             };

   

    //NSString *jiekoujianding=@"https://api.ai.qq.com/path/to/api";
    NSString *jiekoujianding =@"https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr";

    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    [manger POST:jiekoujianding parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"responseObject==%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"error==%@",error);
    }];

    [self zidianpaixu];

 
}

- (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

    NSData *base64Data = [data base64EncodedDataWithOptions:0];

    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];

    return baseString;
}


-(void)zidianpaixu{

    NSInteger timeCount=[[HBValidateM getCurrentTimes] integerValue]/1000;


    UIImage *originImage = [UIImage imageNamed:@"1000.png"];
    NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
    NSString *encodedImageStr = [data base64Encoding];
    
    //NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSString *urlEncodingString = [encodedImageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //uppercaseString];





    NSString *timeStr=[NSString stringWithFormat:@"%zd",timeCount];

    NSString *randomStr=[self createUuid];

    NSDictionary *dict = @{
                              @"app_id":@"1106795032",
                              @"image":urlEncodingString,
                              @"time_stamp":timeStr,
                              @"nonce_str":randomStr,
                             //@"sign":@"73A0720EAF720F138B78F93D65AE673A"
                             };

    NSArray *allKeyArray = [dict allKeys];
    /// 降序
//    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//        NSComparisonResult resuest = [obj2 compare:obj1];
//        return resuest;
//    }];
    /// 生序
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);

    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
//    NSLog(@"valueArray:%@",valueArray);


    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        NSString *keyValue = [NSString stringWithFormat:@"%@=%@",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:keyValue];
    }

    //signString用于签名的原始参数集合
    NSString *signString = [signArray componentsJoinedByString:@"&"];

    NSString *appendStr=[signString stringByAppendingString:@"&app_key=zvVIWBt07Tl3uQlM"];

    NSString *md5result = [[self md5:appendStr] uppercaseString];

    NSLog(@"signString MD5====:%@",md5result);

}


#pragma mark ======= 随机数
-(NSString*)createUuid;
{
    char data[10];
    for (int x=0;x<10;data[x++] = (char)('A' + (arc4random_uniform(26))));

    return [[NSString alloc] initWithBytes:data length:10 encoding:NSUTF8StringEncoding];
}

#pragma mark ======= MD5
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];

    return  output;
}


-(void)chooseImage{

    //调用系统相册的类
    UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
    //设置选取的照片是否可编辑
    pickerController.allowsEditing = YES;
    //设置相册呈现的样式
    UIAlertController *alertCtro=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    [alertCtro addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        //调取摄像头
        pickerController.sourceType =  UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:pickerController animated:YES completion:nil];


    }]];

    [alertCtro addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        pickerController.sourceType =  UIImagePickerControllerSourceTypeSavedPhotosAlbum;//图片分组列表样式

        [self presentViewController:pickerController animated:YES completion:nil];



    }]];

    [alertCtro addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {


        [self dismissViewControllerAnimated:YES completion:nil];

    }]];

    pickerController.delegate = self;
    //使用模态呈现相册
    [self presentViewController:alertCtro animated:YES completion:^{}];


}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    UIImage *resultImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    UIImage *image = [resultImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];


    NSInteger timeCount=[[HBValidateM getCurrentTimes] integerValue]/1000;

    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    NSMutableDictionary *dictM=[NSMutableDictionary dictionary];

    dictM[@"app_id"]=@"1106795032";
    dictM[@"image"]=encodedImageStr ;
    dictM[@"nonce_str"]=@"fa577ce340859f9fe";
    NSString *timeStr=[NSString stringWithFormat:@"%zd",timeCount];
    dictM[@"time_stamp"]=timeStr;
    dictM[@"sign"]=@"";
    dictM[@"app_key"]=@"zvVIWBt07Tl3uQlM";

    //OCR --->
    [HYBNetworking postWithUrl:@"https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr" refreshCache:YES params:dictM success:^(id response) {

        NSLog(@" OCR --->成功==== %@",response);


        NSArray *dictArry=@[@{
                                @"MobileCode":@"15111220570",
                                @"Name":@"zengw",
                                @"CommitContent":@"田农八部"
                                }];

        NSMutableDictionary *dictM=[NSMutableDictionary dictionary];

        dictM[@"Id"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_messageId"];
        dictM[@"Token"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_token"];
        dictM[@"AddMobilePhoneDetails"]= [dictArry mj_JSONString];

        // 上传拍照解析到的数据
        [HYBNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",host_api,AddMobilePhone_api] refreshCache:YES params:dictM success:^(id response) {

            NSLog(@"拍照解析到的数据上传成功==== %@",response);
        } fail:^(NSError *error) {

            NSLog(@"拍照解析到的数据上传失败==== %@",error);
        }];



    } fail:^(NSError *error) {

        NSLog(@"  OCR ---> %@",error);
    }];


    [self dismissViewControllerAnimated:YES completion:nil];

}

@end
